<template>
  <div class="users-page">
    <div class="page-header">
      <h2>邻里用户</h2>
      <p class="page-description">管理社区内所有注册用户信息及状态</p>
    </div>

    <div class="table-controls">
      <div class="search-box">
        <i class="fas fa-search"></i>
        <input
            v-model="searchQuery"
            type="text"
            placeholder="搜索昵称、手机号、用户ID、住址..."
            class="search-input"
            @input="handleSearch"
        />
        <select v-model="userStatus" class="status-select" @change="handleSearch">
          <option value="all">所有状态</option>
          <option :value="1">正常</option>
          <option :value="0">禁用</option>
        </select>
        <select v-model="genderStatus" class="gender-select" @change="handleSearch">
          <option value="0">所有类别</option>
          <option :value="1">男</option>
          <option :value="2">女</option>
        </select>
      </div>
    </div>

    <div class="user-table-container">
      <table>
        <thead>
        <tr>
          <th>ID</th>
          <th>头像</th>
          <th>昵称</th>
          <th>注册时间</th>
          <th>手机号</th>
          <th>性别</th>
          <th>楼栋号</th>
          <th>单元号</th>
          <th>房间号</th>
          <th>积分余额</th>
          <th>创建时间</th>
          <th>状态</th>
          <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="user in paginatedUsers" :key="user.userId" class="table-row">
          <td>{{ user.userId }}</td>
          <td>
            <img :src="user.avatar || defaultAvatar" alt="用户头像" class="user-avatar-sm" />
          </td>
          <td>{{ user.nickname }}</td>
          <td>{{ formatDateTime(user.createdAt) }}</td>
          <td>{{ user.phone }}</td>
          <td>
            <span class="gender-badge">{{ user.gender == 1 ? '男' : '女' }}</span>
          </td>
          <td>{{ user.building }}</td>
          <td>{{ user.unit }}</td>
          <td>{{ user.room }}</td>
          <td class="points">{{ user.points }}</td>
          <td>{{ formatDateTime(user.updatedAt) }}</td>
          <td>
              <span
                  :class="['status-badge', user.status === 1 ? 'status-active' : 'status-inactive']"
              >{{ user.status === 1 ? '正常' : '禁用' }}</span>
          </td>
          <td class="action-cell">
            <button @click="showUser(user)" class="action-btn view-btn">
              <i class="fas fa-eye"></i> 查看
            </button>
            <button @click="changeStatus(user.userId)"
                    class="action-btn"
                    :class="user.status === 1 ? 'disable-btn' : 'enable-btn'"
            >
              <i :class="user.status === 1 ? 'fas fa-lock' : 'fas fa-unlock'"></i>
              {{ user.status === 1 ? '禁用' : '启用' }}
            </button>
          </td>
        </tr>
        </tbody>
      </table>

      <div class="pagination-container">
        <Pagination
            :currentPage="data.currentPage"
            :totalPages="data.totalPages"
            @page-changed="handlePageChange"
        />
      </div>
    </div>

    <el-dialog
        :close-on-click-modal="false"
        v-model="data.isShow"
        title="用户详情"
        width="50%"
        :before-close="() => data.isShow = false"
    >
      <div class="detail-header">
        <img :src="data.detailForm.avatar || defaultAvatar" alt="用户头像" class="detail-avatar" />
        <div class="detail-header-info">
          <h3>{{ data.detailForm.nickname }}</h3>
          <span :class="['status-badge', data.detailForm.status === 1 ? 'status-active' : 'status-inactive']"
                style="margin-left: 10px;">
            {{ data.detailForm.status === 1 ? '正常' : '禁用' }}
          </span>
        </div>
      </div>

      <el-form label-width="120px" class="detail-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户ID">
              <el-input readonly v-model="data.detailForm.userId"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号">
              <el-input readonly v-model="data.detailForm.phone"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别">
              <el-input
                  readonly
                  :value="data.detailForm.gender == 1 ? '男' : '女'"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="积分余额">
              <el-input readonly v-model="data.detailForm.points"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="楼栋号">
              <el-input readonly v-model="data.detailForm.building"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单元号">
              <el-input readonly v-model="data.detailForm.unit"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="房间号">
              <el-input readonly v-model="data.detailForm.room"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="注册时间">
              <el-input readonly v-model="data.detailForm.createdAt"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="修改时间">
              <el-input readonly v-model="data.detailForm.updatedAt"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item class="form-actions">
          <el-button type="primary" @click="data.isShow = false">确认</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive, onMounted } from 'vue';
import Pagination from '@/components/Pagination.vue';
import axios from "@/utils/axios.ts";

// 所有原有变量保持不变
const searchQuery = ref('');
const userStatus = ref('all');
const genderStatus = ref('0');
const allUsers = ref([]);
const defaultAvatar = ref('https://picsum.photos/200/200?random=1'); // 默认头像

// 处理搜索方法保持不变
const handleSearch = () => {
  data.currentPage = 1;
  fetchUsers();
};

// 查看用户详情方法保持不变
const showUser = (user) => {
  data.isShow = true;
  data.detailForm = { ...user };
  data.detailForm.createdAt = formatDateTime(user.createdAt);
  data.detailForm.updatedAt = formatDateTime(user.updatedAt);
};

// 响应式数据
const data = reactive({
  currentPage: 1,
  usersPerPage: 5,
  totalPages: 1,
  isShow: false,
  detailForm: {
    userId: '',
    avatar: '',
    nickname: '',
    createdAt: '',
    phone: '',
    gender: '',
    building: '',
    unit: '',
    room: '',
    points: '',
    updatedAt: '',
    status: 0,
  }
});

// 分页处理保持不变
const paginatedUsers = computed(() => {
  const start = (data.currentPage - 1) * data.usersPerPage;
  const end = start + data.usersPerPage;
  return allUsers.value.slice(start, end);
});

// 分页切换方法保持不变
const handlePageChange = (page) => {
  data.currentPage = page;
  fetchUsers();
};

// 更改用户状态方法保持不变
const changeStatus = (userId) => {
  axios.put(`/api/users/${userId}/status`)
      .then(res => {
        if (res.code == 200) {
          fetchUsers();
        }
      })
      .catch(err => console.error('状态更新失败', err));
};

// 格式化日期时间方法保持不变
const formatDateTime = (dateTime) => {
  if (!dateTime) return '';
  const date = new Date(dateTime);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 获取用户数据保持不变
const fetchUsers = () => {
  const params = {
    info: searchQuery.value.trim(),
    status: userStatus.value,
    gender: genderStatus.value,
    page: data.currentPage,
    limit: data.usersPerPage
  };

  axios.post("/api/users/findUsers", params)
      .then(res => {
        if (res.code == 200) {
          allUsers.value = res.data;
          const calculatedPages = Math.ceil(allUsers.value.length / data.usersPerPage);
          data.totalPages = calculatedPages > 0 ? calculatedPages : 1;
        } else {
          console.log("搜索失败：", res);
          allUsers.value = [];
          data.totalPages = 1;
        }
      })
      .catch(err => {
        console.error("请求出错：", err);
        allUsers.value = [];
        data.totalPages = 1;
      });
};

// 初始化加载数据保持不变
const init = () => {
  fetchUsers();
  axios.get(`/api/users?page=${data.currentPage}&limit=${data.usersPerPage}`)
      .then(res => {
        console.log("响应数据: ", res.data)
        allUsers.value = res.data.records;
        data.totalPages = res.data.total > 0 ? res.data.total : 1;
      })
};

onMounted(() => {
  init();
});
</script>

<style scoped>
/* 页面整体样式优化 */
.users-page {
  padding: 20px 30px;
  background-color: #f9fafb;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 25px;
}

.page-header h2 {
  color: #1e293b;
  font-size: 22px;
  margin-bottom: 8px;
  font-weight: 600;
}

.page-description {
  color: #64748b;
  font-size: 14px;
  margin: 0;
}

/* 搜索区域样式优化 */
.table-controls {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 15px;
  flex-wrap: wrap;
}

.search-box {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;
  max-width: 800px;
}

.search-input {
  padding: 10px 15px 10px 38px;
  width: 100%;
  max-width: 400px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  transition: all 0.2s ease;
}

.search-input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.search-box i.fas.fa-search {
  position: relative;
  left: 30px;
  color: #94a3b8;
  z-index: 1;
}

.status-select, .gender-select {
  padding: 10px 15px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  background-color: white;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.status-select:focus, .gender-select:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

/* 表格容器样式优化 */
.user-table-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -1px rgba(0, 0, 0, 0.03);
  overflow: hidden;
}

/* 表格样式优化 */
table {
  width: 100%;
  border-collapse: collapse;
  text-align: left;
}

thead {
  background-color: #f1f5f9;
}

thead tr th {
  padding: 14px 15px;
  color: #334155;
  font-weight: 600;
  font-size: 13px;
  position: relative;
  white-space: nowrap;
}

thead tr th:not(:last-child)::after {
  content: '';
  position: absolute;
  right: 0;
  top: 10px;
  height: 24px;
  width: 1px;
  background-color: #e2e8f0;
}

tbody tr.table-row {
  transition: background-color 0.2s ease;
  border-bottom: 1px solid #f1f5f9;
}

tbody tr.table-row:hover {
  background-color: #f8fafc;
}

th, td {
  padding: 14px 15px;
  font-size: 14px;
  color: #334155;
}

/* 头像样式优化 */
.user-avatar-sm {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #f1f5f9;
}

/* 徽章样式优化 */
.status-badge {
  display: inline-block;
  padding: 3px 10px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  text-transform: capitalize;
}

.status-active {
  background-color: #dcfce7;
  color: #166534;
}

.status-inactive {
  background-color: #fee2e2;
  color: #991b1b;
}

.gender-badge {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
  background-color: #e0f2fe;
  color: #0369a1;
}

/* 积分样式 */
.points {
  color: #b45309;
  font-weight: 500;
}

/* 操作按钮样式优化 */
.action-cell {
  display: flex;
  gap: 8px;
}

.action-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 13px;
  font-weight: 500;
  color: white;
  display: inline-flex;
  align-items: center;
  gap: 5px;
  transition: all 0.2s ease;
}

.view-btn {
  background-color: #3b82f6;
}

.view-btn:hover {
  background-color: #2563eb;
}

.disable-btn {
  background-color: #ef4444;
}

.disable-btn:hover {
  background-color: #dc2626;
}

.enable-btn {
  background-color: #10b981;
}

.enable-btn:hover {
  background-color: #059669;
}

/* 分页容器样式 */
.pagination-container {
  padding: 15px 20px;
  border-top: 1px solid #f1f5f9;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 无数据样式 */
.no-data td {
  text-align: center;
  padding: 60px 20px !important;
  color: #94a3b8;
  background-color: #f8fafc;
}

.no-data p {
  margin: 0;
  font-size: 14px;
}

/* 详情弹窗样式优化 */
.detail-header {
  display: flex;
  align-items: center;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f1f5f9;
}

.detail-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid #f1f5f9;
}

.detail-header-info {
  margin-left: 15px;
}

.detail-header-info h3 {
  margin: 0 0 5px 0;
  font-size: 18px;
  color: #1e293b;
  display: flex;
  align-items: center;
}

.detail-form .el-form-item {
  margin-bottom: 18px;
}

.detail-form .el-input {
  width: 100%;
}

.form-actions {
  margin-top: 15px;
  text-align: right;
}

.form-actions .el-button {
  padding: 8px 20px;
}
</style>
